//
//  YBSetChargeView.m
//  WuyouTang
//
//  Created by YB007 on 2019/11/27.
//  Copyright © 2019 cat. All rights reserved.
//

#import "YBSetChargeView.h"

@interface YBSetChargeView()<UITextFieldDelegate>

@end

@implementation YBSetChargeView

- (void)awakeFromNib {
    [super awakeFromNib];
    
    UIImageView *rightView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 12.5, 40, 15)];
    rightView.contentMode = UIViewContentModeScaleAspectFit;
    rightView.image = [UIImage imageNamed:@"礼物-金币"];
    _chargeTF.rightView = rightView;
    _chargeTF.rightViewMode = UITextFieldViewModeAlways;
    
    _titleL.text = YZMsg(@"请输入收费金额");
    _tipsL.text = YZMsg(@"*收取金额不可为小数");
    [_sureBtn setTitle:YZMsg(@"确认") forState:0];
    
    
}

+(instancetype)showInputView:(NSString *)price complete:(YBSetChargeBlock)complete;{
    YBSetChargeView *cV = [[[NSBundle mainBundle]loadNibNamed:@"YBSetChargeView" owner:nil options:nil] objectAtIndex:0];
    
    if (complete) {
        cV.chargeEvent = ^(NSString * _Nonnull priceStr) {
            complete(priceStr);
        };
    }
    [cV setUpView:price];
    return cV;
}
-(void)setUpView:(NSString *)priceStr {
    self.frame = [UIScreen mainScreen].bounds;
    
    _chargeTF.tintColor = RGB_COLOR(@"#323232", 1);
    _chargeTF.keyboardType = UIKeyboardTypeNumberPad;
    _chargeTF.delegate = self;
    _chargeTF.placeCol = RGB_COLOR(@"#969696", 1);
    _chargeTF.placeholder = YZMsg(@"请输入收取金额");
    _chargeTF.text = priceStr;
    _chargeTF.textColor = RGB_COLOR(@"#323232", 1);
    _chargeTF.font = SYS_Font(13);
    
    [[UIApplication sharedApplication].delegate.window addSubview:self];
    
    [UIView animateWithDuration:0.3 animations:^{
        
    } completion:^(BOOL finished) {
        self.backgroundColor = RGB_COLOR(@"#000000", 0.4);
    }];
}

-(void)dismiss {
   [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self removeFromSuperview];
}

- (IBAction)clickCancleBtn:(id)sender {
    [self dismiss];
}
- (IBAction)clickSureBtn:(id)sender {
    if (self.chargeEvent) {
        self.chargeEvent(_chargeTF.text);
    }
    [self dismiss];
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == _chargeTF) {
        //新输入的
        if (string.length == 0) {
            return YES;
        }
        NSString *checkStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
        NSString *regex = @"^[1-9]\\d*|0$";
        return [self isValid:checkStr withRegex:regex];
    }
    return YES;
}
//检测改变过的文本是否匹配正则表达式，如果匹配表示可以键入，否则不能键入
- (BOOL) isValid:(NSString*)checkStr withRegex:(NSString*)regex {
    NSPredicate *predicte = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [predicte evaluateWithObject:checkStr];
}
@end
